/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-07-31 21:26:49
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-01 00:32:47
 * @FilePath: /110/36/testThread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <vector>
class Task
{
public:
    Task() {}

    void SerData(int x, int y)
    {
        datax = x;
        datay = y;
    }

    ~Task() {}

    int Excute()
    {
        return datax + datay;
    }

private:
    int datax;
    int datay;
};

class ThreadData
{
public:
    ThreadData(int x, int y, const std::string threadname) : _threadname(threadname)
    {
        _t.SerData(x, y);
    }

    std::string threadname()
    {
        return _threadname;
    }

    int run()
    {
        return _t.Excute();
    }

private:
    std::string _threadname;
    Task _t;
};

class Result
{
public:
    Result() {}
    ~Result() {}

    void SetResult(int result, const std::string threadname)
    {
        _result = result;
        _threadname = threadname;
    }

    void Print()
    {
        std::cout << "Thread name: " << _threadname << " result: " << _result << std::endl;
    }

private:
    int _result;
    std::string _threadname;
};

void* handler(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);

    std::string name = td->threadname();

    Result *res = new Result();
    int result = td->run();

    res->SetResult(result, name);

    delete td;

    sleep(2);
    return res;

    return nullptr;
}

int main()
{
    std::vector<pthread_t> threads;
    for (int i = 0; i < 5; ++i)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "Thread-%d", i + 1);
        ThreadData *td = new ThreadData(10, 20, threadname);

        pthread_t rid;
        pthread_create(&rid, nullptr, handler, td);
        threads.push_back(rid);
    }

    std::vector<Result *> res;
    void *ret = nullptr;
    for (auto &tid : threads)
    {
        pthread_join(tid, &ret);
        res.push_back((Result *)ret);
    }

    for (auto &r : res)
    {
        r->Print();
        delete r;
    }
}

// void* newthreadrun(void* args)
// {
//     while(1)
//     {
//         std::cout<< "I am new tread,pid: " << getpid() <<std::endl;
//         sleep(1);
//     }

//     return nullptr;
// }

// int main()
// {
//     pthread_t tid;
//     pthread_create(&tid,nullptr,newthreadrun,nullptr);

//     while(1)
//     {
//         std::cout<< "I am main tread,pid: " << getpid() <<std::endl;
//         sleep(1);
//     }

//     return 0;
// }